﻿/*综合文档管理
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jw.Web.App_Start;
using System.Web.Http;
using Jw.Core;
using Jw.Models;
using System.IO;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;

namespace Jw.Web.Areas.Qms.Controllers
{
    public class FileContentController : BaseController
    {
        //
        // GET: /Qms/FileContent/
        public ActionResult Index()
        {
            return View();
        }

        //
        public ActionResult UpLoad(string id)
        {
            ViewBag.FileId = id;
            return View();
        }

        public void DownLoad(string id)
        {
            q_FileAttachmentService service = new q_FileAttachmentService();
            q_FileAttachment obj = service.GetModel(new ParamQuery().AndWhere("FileAttachment_FileBh", id));
            string filePath = Server.MapPath("~/Upload/") + obj.FileAttachment_Path;
            Jw.Utils.ZFiles.DownloadFile(System.Web.HttpContext.Current, filePath, 1024102410);
        }

    }

    //api/qms/Filecontent  
    public class FileContentApiController : ApiController
    {
        public dynamic Get(RequestWrapper request)
        {
            request.LoadSettingXmlString(@"
            <settings defaultOrderBy='FileContent_FileBh'>
               <where>
                    <field name='FileContent_TypeBh' cp='equal' ignoreEmpty='true'></field>
                </where>
            </settings>");
            var service = new q_FileContentService();
            var result = service.GetModelListWithPaging(request.ToParamQuery());
            return result;
        }

        public dynamic GetFileTypes(RequestWrapper request)
        {
            request.LoadSettingXmlString(@"
           <settings defaultOrderBy='FileType_Bh'>
               <where defaultIgnoreEmpty='true'>
                    <field name='FileType_Bh'      cp='equal'></field>
                    <field name='FileType_Mc'  cp='like' ></field>
                </where>
            </settings>
            ");

            var result = new q_FileTypeService().GetDynamicList(request.ToParamQuery());
            return result;
        }

        public string GetNewCode()
        {
            //var service = new mms_materialService();
            //return service.GetNewMaterialCode(id);
            return new q_FileContentService().GetNewKey("FileContent_FileBh", "dateplus");
        }

        [System.Web.Http.HttpPost]
        public void Edit(dynamic data)
        {
            var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
        <settings>
            <table>
                q_FileContent
            </table>
            <where>
                <field name='FileContent_FileBh' cp='equal' ></field>
            </where>
        </settings>"
              );

            var service = new q_FileContentService();
            var result = service.Edit(null, listWrapper, data);

        }

        [System.Web.Http.HttpPost]
        public void EditFileType(dynamic data)
        {
            var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>q_FileType</table>
                <where>
                    <field name='FileType_Bh' cp='equal'></field>
                </where>
            </settings>
            ");
            var service = new q_FileTypeService();
            var result = service.Edit(null, listWrapper, data);

        }


        [System.Web.Http.HttpPost]
        public dynamic postfile()
        {
            // 设置上传目录
            // var provider = new MultipartFormDataStreamProvider(@"D:\");
            // 接收数据，并保存文件
            // Request.Content.ReadAsMultipartAsync(provider);
            string id = string.Empty;
            try
            {
                var context = HttpContext.Current;
                var request = context.Request;

                id = request.Params["Id"];
                //保存文件
                var postFile = request.Files[0];
                string uploadPath = HttpContext.Current.Server.MapPath("~/Upload/");
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);
                string filePath = postFile.FileName.Substring(postFile.FileName.LastIndexOf("\\") + 1);
                string fileType = filePath.Substring(filePath.LastIndexOf("."));
                filePath = filePath.Substring(0, filePath.LastIndexOf("."));
                string fullfilePath = uploadPath + filePath + DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond + fileType;
                //存储文件
                request.Files[0].SaveAs(fullfilePath);

                ////把文件转成流存储到数据库
                //Stream stream = request.Files[0].InputStream;
                //byte[] bytes = new byte[stream.Length];
                //stream.Read(bytes, 0, bytes.Length);
                //// 设置当前流的位置为流的开始
                //stream.Seek(0, SeekOrigin.Begin);
                //stream.Close();

                var service = new q_FileAttachmentService();
                var service2 = new q_FileContentService();
                //删除该记录下同名的文件
                int i = service.Delete(new ParamDelete().AndWhere("FileAttachment_FileBh", id));//.AndWhere("FileAttachment_FullName", filePath));
                service2.Update(new ParamUpdate().Column("FileContent_Fjsl", 0).AndWhere("FileContent_FileBh", id));

                string rowId = service.GetNewKey("FileAttachment_RowId", "max", 1, new ParamQuery().AndWhere("FileAttachment_FileBh", id));
                string sPath = fullfilePath.Substring(uploadPath.Length, fullfilePath.Length - uploadPath.Length);
                i = service.Insert(new ParamInsert()
                     .Column("FileAttachment_FileBh", id)
                     .Column("FileAttachment_RowId", rowId)
                     .Column("FileAttachment_Path", sPath)
                     .Column("FileAttachment_FullName", filePath));

                //更新附件编号
                service2.Update(new ParamUpdate().Column("FileContent_Fjsl", 1).AndWhere("FileContent_FileBh", id));
                //
            }
            catch (System.Exception e)
            {
                var o = new { success = false, message = e.Message };
                return new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(o), System.Text.Encoding.UTF8, "text/html") };
            }

            //返回前台
            //return new { success = true, message = "导入成功!" };
            var obss = new { success = true, message = "导入成功!" };
            //以下这种方式返回值 ，FireFox下不报错。 "{\"success\":true,\"message\":\"保存成功！\"}"
            var resp = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(obss), System.Text.Encoding.UTF8, "text/html") };
            return resp;
        }


    }
}
